package com.bian.security.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author bianpengfei
 * @create 2019-02-06 17:52
 **/

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    // 定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("VIP1","VIP2","VIP3")
                .and()
                .withUser("lisi").password("123456").roles("VIP2")
                .and()
                 .withUser("wangwu").password("123456").roles("VIP1");
    }

    // 定义授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 定制请求的授权规则
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("VIP1")
                .antMatchers("/level2/**").hasRole("VIP2")
                .antMatchers("/level3/**").hasRole("VIP3");

        // 开启自动配置的登录功能，如果没有登录，就会来到登录页面
        // 1、/login来到登录页
        // 2、没有登录表示重定向到/login?error，登录失败
        http.formLogin();

        // 开启自动配置注销功能
        // 注销成功会返回 /login?logout 页面
        // logoutSuccessUrl表示注销成功来到的页面
        http.logout().logoutSuccessUrl("/").invalidateHttpSession(true);

    }
}
